<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      canvas {
        border: 1px solid #000;
        width: 1000px;
        height: 400px;
      }
    </style>
  </head>
  <body>
    <canvas id="canvas"></canvas>

    <script>
      const createBall = () => {
        return {
          x: Math.random() * 800 + 10,
          y: Math.random() * 350 + 10,
          vx: Math.random() * 1 + 2,
          vy: 2,
          radius: 5,
          color: '#ff002253',
          draw: function () {
            ctx.beginPath()
            ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, true)
            ctx.closePath()
            ctx.fillStyle = this.color
            ctx.fill()
          },
        }
      }
      
      let ballList = []
      for(let i = 0; i < 5; i ++) {
       ballList.push(createBall())

      }
      
      const updateBallList = () => {
        ballList.forEach((ball) => {
          ball.draw()
          if (ball.x + ball.vx > canvas.width - 20) {
            // ball.vx = -ball.vx
            ball.x = Math.random() * 800
            ball.y = Math.random() * 70 + 20
          }
          ball.x += ball.vx
        })
      }
      
      var canvas = document.getElementById('canvas')
      var ctx = canvas.getContext('2d')
      var raf


      function draw() {
        ctx.fillStyle = 'rgba(255,255,255,0.3)'
        ctx.fillRect(0, 0, canvas.width, canvas.height)
        updateBallList()

        raf = window.requestAnimationFrame(draw)
      }

      // canvas.addEventListener('mouseover', function (e) {
      //   raf = window.requestAnimationFrame(draw)
      // })

      // canvas.addEventListener('mouseout', function (e) {
      //   window.cancelAnimationFrame(raf)
      // })
      window.requestAnimationFrame(draw)

      ballList.forEach(ball => ball.draw())
    </script>
  </body>
</html>
